package com.zzs.group.manager.command;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.zzs.group.manager.Manager;
import com.zzs.group.manager.enums.GroupMemberLevelEnum;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.console.command.CommandSender;
import net.mamoe.mirai.console.command.java.JRawCommand;
import net.mamoe.mirai.contact.*;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import net.mamoe.mirai.utils.MiraiLogger;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class ExportGroupObjectCommand extends JRawCommand {
    private MiraiLogger logger = Manager.INSTANCE.getLogger();
    public static final int PARTITION_SIZE = 200;

    public ExportGroupObjectCommand() {
        super(Manager.INSTANCE, "导出");
        setPrefixOptional(true);
    }

    @Override
    public void onCommand(@NotNull CommandSender sender, @NotNull MessageChain args) {
        Contact subject = sender.getSubject();
        long userId = sender.getUser().getId();

        if (!(userId == 875310790 || userId == 627326418)) {
            logger.info("qq号：" + userId + "无权使用导出命令");
            return;
        }
        String param = args.contentToString();
        logger.info("导出群成员 参数：" + param);
        long groupId;
        try {
            groupId = Long.parseLong(param);
        } catch (Exception e) {
            logger.info("参数类型不正确");
            return;
        }

        Bot bot = sender.getBot();
        ContactList<Group> groups = bot.getGroups();
        List<Long> groupIdList = groups.stream()
                .map(Group::getId)
                .collect(Collectors.toList());
        logger.info("所加入的群列表 ：" + groupIdList);
        if (!groupIdList.contains(groupId)) {
            logger.info("Bot群列表钟未找到该群号");
            return;
        }

        Optional<Group> first = groups.stream()
                .filter(s -> s.getId() == groupId)
                .findFirst();
        if (!first.isPresent()) {
            logger.info("Bot群列表钟未找到该群号");
            return;
        }
        Group group = first.get();
        ContactList<NormalMember> groupMembers = group.getMembers();

        List<String> groupMemberList = new ArrayList<>();
        for (NormalMember groupMember : groupMembers) {
            StringBuilder stringBuilder = new StringBuilder();
            long id = groupMember.getId();
            String nick = groupMember.getNick();
            String nameCard = groupMember.getNameCard();
            MemberPermission permission = groupMember.getPermission();
            int joinTimestamp = groupMember.getJoinTimestamp();
            int lastSpeakTimestamp = groupMember.getLastSpeakTimestamp();
            logger.info("lastSpeakTimestamp :" + lastSpeakTimestamp);
            //转化成日期
            Date date = new Date(joinTimestamp * 1000L);
            String joinTime = DateUtil.format(date, DatePattern.NORM_DATE_PATTERN);
            Date lastSpeakDate = new Date(lastSpeakTimestamp * 1000L);
            String lastSpeakTime = DateUtil.format(lastSpeakDate, DatePattern.NORM_DATETIME_FORMATTER);
            int level = permission.getLevel();
            String levelName = GroupMemberLevelEnum.getLevelName(level);
            stringBuilder
                    .append(joinTime)
                    .append(" | ").append(levelName)
                    .append(" | ").append(lastSpeakTime)
                    .append(" | ").append(id)
                    .append(" | ").append(nick)
                    .append(" | ").append(nameCard)
            ;
            groupMemberList.add(stringBuilder.toString());
        }

        List<List<String>> partition = ListUtil.partition(groupMemberList, PARTITION_SIZE);
        for (List<String> messageList : partition) {
            MessageChainBuilder messageChainBuilder = new MessageChainBuilder();
            for (String message : messageList) {
                messageChainBuilder.append(message)
                        .append(System.lineSeparator());
            }
            String singleMessages = messageChainBuilder.build().toString();
            subject.sendMessage(singleMessages);
        }


    }

}
